using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Admin.NET.Application.DL645;
using Admin.NET.Application.Entity.Business;
using Admin.NET.Application.Enums;
using Admin.NET.Application.Mqtt.mqttresponse;
using Admin.NET.Application.Service.Electricity;
using Admin.NET.Application.Util;
using Admin.NET.Core;
using Furion.FriendlyException;
using Furion.Schedule;
using Microsoft.Extensions.DependencyInjection;

namespace Admin.NET.Application.Job;

[JobDetail("job_readruixxingmeter", Description = "瑞兴电表读取", GroupName = "default", Concurrent = false)]
[PeriodMinutes(50L, TriggerId = "trigger_readruixxingmeter", Description = "瑞兴电表读取", RunOnStart = true)]
public class ReadRuiXingMeter : IJob
{
	private readonly IServiceScopeFactory _scopeFactory;

	public ReadRuiXingMeter(IServiceScopeFactory scopeFactory)
	{
		_scopeFactory = scopeFactory;
	}

	public async Task ExecuteAsync(JobExecutingContext context, CancellationToken stoppingToken)
	{
		using IServiceScope serviceScope = _scopeFactory.CreateScope();
		SqlSugarRepository<ElectricMeter> meterServer = serviceScope.ServiceProvider.GetService<SqlSugarRepository<ElectricMeter>>();
		List<ElectricMeter> listMeter = await (from u in meterServer.AsQueryable()
			where u.BrandId == 38020630857989L
			select u).ToListAsync();
		DL645Agreement dL645Agreement = new DL645Agreement();
		Thread.Sleep(10000);
		foreach (ElectricMeter item in listMeter)
		{
			(IAggrementPlugin, BrandModel) plugin = AggrementPluginUtil.GetPlugin(item);
			var (pluginService, _) = plugin;
			_ = plugin.Item2;
			Dictionary<string, UploadMqttInfo> dic = new Dictionary<string, UploadMqttInfo>();
			UploadMqttInfo uploadMqttInfo = new UploadMqttInfo();
			EPowerService ePowerService = new EPowerService();
			string allRotal = (uploadMqttInfo.TotalE = (uploadMqttInfo.Alltotal = pluginService.ReadCombinedTotalE(item.Sn, item.LowAddr, "RuiXing")));
			if (string.IsNullOrEmpty(allRotal))
			{
				await ePowerService.MeterOffline(item.Sn, 0);
				return;
			}
			Thread.Sleep(1000);
			byte[] byteinfo = dL645Agreement.Send645Agreement(AgreementaType.Reading, item.LowAddr, "36383337").ToArray();
			string bodylhz = await pluginService.Transform(valueCmd: string.Join("", from u in byteinfo.ToArray()
				select u.ToString("X2")), imei: item.Sn);
			if (!string.IsNullOrEmpty(bodylhz))
			{
				string valuelz = ParseDLT645Result(bodylhz);
				if (IsHexadecimal(valuelz))
				{
					string info = Convert.ToString(Convert.ToInt32(valuelz, 16), 2).PadLeft(8, '0');
					string isLhz = ((info.Substring(3, 1) == "0") ? "0000" : "0050");
					uploadMqttInfo.State = isLhz;
				}
			}
			Thread.Sleep(1000);
			byte[] byteinfody = dL645Agreement.Send645Agreement(AgreementaType.Reading, item.LowAddr, "33323435").ToArray();
			uploadMqttInfo.VoltageAll = ParseDLT645Result(await pluginService.Transform(valueCmd: string.Join("", from u in byteinfody.ToArray()
				select u.ToString("X2")), imei: item.Sn));
			Thread.Sleep(1000);
			byte[] byteinfodl = dL645Agreement.Send645Agreement(AgreementaType.Reading, item.LowAddr, "33323535").ToArray();
			uploadMqttInfo.CurrentAll = ParseDLT645Result(await pluginService.Transform(valueCmd: string.Join("", from u in byteinfodl.ToArray()
				select u.ToString("X2")), imei: item.Sn));
			Thread.Sleep(1000);
			byte[] byteinfogl = dL645Agreement.Send645Agreement(AgreementaType.Reading, item.LowAddr, "33323635").ToArray();
			uploadMqttInfo.ActivePowerAll = ParseDLT645Result(await pluginService.Transform(valueCmd: string.Join("", from u in byteinfogl.ToArray()
				select u.ToString("X2")), imei: item.Sn));
			dic.Add(item.LowAddr, uploadMqttInfo);
			int newtype = 0;
			await ePowerService.MeterUpload(item.Sn, newtype, dic);
		}
	}

	private bool IsHexadecimal(string input)
	{
		string pattern = "^[A-Fa-f0-9]+$";
		return Regex.IsMatch(input, pattern);
	}

	private string ParseDLT645Result(string body)
	{
		if (string.IsNullOrWhiteSpace(body))
		{
			return "";
		}
		List<byte> list = new List<byte>();
		list.Add(254);
		list.Add(254);
		list.Add(254);
		list.Add(254);
		bool sucess = true;
		for (int i = 0; i < body.Length / 2; i++)
		{
			byte byteInfo = (byte)Convert.ToInt32(body.Substring(i * 2, 2), 16);
			if (!(byteInfo == 254 && sucess))
			{
				sucess = false;
				list.Add(byteInfo);
			}
		}
		AgreementAnalysis resultInfo = DL645Agreement.DL645Analysis(list.ToArray());
		if (!resultInfo.Sucess)
		{
			throw Oops.Oh(ErrorCodeEnumEx.X1001);
		}
		if (!string.IsNullOrWhiteSpace(resultInfo.Data))
		{
			if (resultInfo.Data.Length > 8)
			{
				string infoType = resultInfo.Data.Substring(0, 8).ToUpper();
				string infoData = resultInfo.Data.Substring(8);
				return DL645ParameterSet.AnalisReading(infoType, infoData);
			}
			return "";
		}
		return "";
	}
}
